package cnt5106.p2p.peer.network;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Vector;
import cnt5106.p2p.common.Logger;
import cnt5106.p2p.peer.filesystem.FileControler;

public class Peer {

	protected String trackerAddr = "127.0.0.1";
	protected int trackerPort = 10240; 
	
	protected PeerClient peerClient = null;
	protected PeerServer peerServer = null;
	protected Thread serverThread = null;
	
	protected Vector<InetSocketAddress> peerList = new Vector<InetSocketAddress>();
	
	protected int clientUDPPort = 0;
	protected int serverUDPPort = 0;
	protected int serverTCPPort = 0;
	
	protected String sharedFile = null; // file that owner shared
	protected String requestedFile = null; // file that peer group request
	
	protected FileControler sharedFileControler = null;
	protected FileControler requestedFileControler = null;
	protected final Object lock = new Object();
	
	protected PEER_STATE STATE;
	
	protected final int subChunkNum = 10;
	
	protected Logger logger;
	
	protected enum PEER_STATE {
		PEER, PEER_GROUP_WAITING, PEER_GROUP_SEEKING,
		PEER_FINISHED,
		FILEOWNER, FILEOWNER_UPLOADING, FILEOWNER_STOP
	}
	
	public Peer() {
	}
	
	public Peer(String peerAddr, int peerPort) throws IOException {
		this.STATE = PEER_STATE.PEER;
		this.clientUDPPort = (int)(Math.random()*(9999-1000+1)+13000);
		this.serverUDPPort = (int)(Math.random()*(9999-1000+1)+13000);
		this.serverTCPPort = (int)(Math.random()*(9999-1000+1)+13000);
		this.peerClient = new PeerClient(this);
		this.peerServer = new PeerServer(this);

		System.out.println("Peer started, " + "ServerUDPPort: " + serverUDPPort);
		this.serverThread = new Thread(peerServer);
		serverThread.start();
		this.peerClient.start();
	}

	public static void main(String[] args) throws Exception {
		if (args.length == 2) {
			String host = args[0];
			int port = Integer.valueOf(args[1]);
			new Peer(host, port);
		} else {
			new Peer("localhost", 9999);
		}
	}
}
